<template>
  <div class="evaluation-detail">
    <div class="header">
      <div class="header-left">
        <el-icon class="back-icon" @click="router.back()">
          <ArrowLeft />
        </el-icon>
        <span class="title">测评详情</span>
      </div>
      <el-button type="primary" size="large" @click="exportReport" :icon="Download">
        导出报告
      </el-button>
    </div>

    <div class="detail-content" v-loading="isLoading">
      <template v-if="reportDetail">
        <div class="section main-section">
          <h2 class="report-title">{{ reportDetail.questionnaire_title }}</h2>
          <div class="total-score">
            <div class="score-label">总分</div>
            <div class="score-value">{{ reportDetail.total_score }}</div>
          </div>
        </div>

        <div class="section">
          <div class="section-title">
            <span class="title-text">心理分析详情</span>
          </div>
          <div v-if="reportDetail.range_results" class="range-list">
            <div
              v-for="(range, rangeName) in reportDetail.range_results"
              :key="rangeName"
              class="range-item"
            >
              <div class="range-header">
                <span class="range-name">【{{ rangeName }}】</span>
                <span class="range-questions">
                  (题目{{ range.start_question_id }}-{{ range.end_question_id }})
                </span>
              </div>
              <div class="range-details">
                <div class="range-score">得分：<span class="highlight">{{ range.total_score }}</span></div>
                <div class="range-status">状态：<span class="highlight">{{ range.mental_status }}</span></div>
                <div class="range-advice">建议：{{ range.advice }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="section">
          <div class="section-title">
            <span class="title-text">完整报告</span>
          </div>
          <div class="report-content">{{ reportDetail.content }}</div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Download } from '@element-plus/icons-vue'
import { Api } from '@/api'
import { Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType } from 'docx'

const route = useRoute()
const router = useRouter()
const reportDetail = ref(null)
const isLoading = ref(false)

// 获取报告详情
const fetchReportDetail = async () => {
  isLoading.value = true
  try {
    const response = await Api.getPsychologyReportDetails({
      id: route.params.id
    })

    if (response.data.status === 200) {
      reportDetail.value = {
        ...response.data.data,
        range_results: response.data.data.range_results || {}
      }
    } else {
      throw new Error(response.data.message || '获取报告详情失败')
    }
  } catch (error) {
    console.error('获取报告详情失败:', error)
    ElMessage.error('获取报告详情失败，请稍后再试')
  } finally {
    isLoading.value = false
  }
}

// 导出报告
const exportReport = async () => {
  try {
    const doc = new Document({
      sections: [{
        properties: {},
        children: [
          new Paragraph({
            text: reportDetail.value.questionnaire_title,
            heading: HeadingLevel.HEADING_1,
            alignment: AlignmentType.CENTER,
          }),
          new Paragraph({
            children: [
              new TextRun({
                text: `总分: ${reportDetail.value.total_score}`,
                bold: true,
              }),
            ],
          }),
          new Paragraph({
            text: '心理分析详情',
            heading: HeadingLevel.HEADING_2,
            alignment: AlignmentType.CENTER,
          }),
          ...Object.entries(reportDetail.value.range_results || {}).map(([rangeName, range]) => [
            new Paragraph({
              children: [
                new TextRun({
                  text: `【${rangeName}】(题目${range.start_question_id}-${range.end_question_id})`,
                  bold: true,
                }),
              ],
            }),
            new Paragraph({
              children: [
                new TextRun({
                  text: `得分: ${range.total_score}`,
                }),
              ],
            }),
            new Paragraph({
              children: [
                new TextRun({
                  text: `状态: ${range.mental_status}`,
                }),
              ],
            }),
            new Paragraph({
              children: [
                new TextRun({
                  text: `建议: ${range.advice}`,
                }),
              ],
            }),
            new Paragraph({ text: '' }),
          ]).flat(),
          new Paragraph({
            text: '完整报告',
            heading: HeadingLevel.HEADING_2,
            alignment: AlignmentType.CENTER,
          }),
          new Paragraph({
            children: [
              new TextRun({
                text: reportDetail.value.content,
              }),
            ],
          }),
        ],
      }],
    })

    const blob = await Packer.toBlob(doc)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `心理报告_${reportDetail.value.questionnaire_title}.docx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('报告导出成功')
  } catch (error) {
    console.error('导出报告失败:', error)
    ElMessage.error('导出报告失败，请稍后再试')
  }
}

onMounted(() => {
  fetchReportDetail()
})
</script>

<style scoped>
.evaluation-detail {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 20px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
}

.back-icon {
  font-size: 24px;
  cursor: pointer;
  margin-right: 16px;
  color: #409EFF;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.detail-content {
  max-width: 900px;
  margin: 20px auto;
  padding: 0 20px;
}

.section {
  background-color: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.main-section {
  text-align: center;
  background: linear-gradient(to bottom, #ffffff, #f8f9fa);
}

.report-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 20px 0;
}

.total-score {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.score-label {
  font-size: 16px;
  color: #606266;
}

.score-value {
  font-size: 36px;
  font-weight: 600;
  color: #409EFF;
}

.section-title {
  position: relative;
  text-align: center;
  margin-bottom: 24px;
}

.title-text {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  position: relative;
  padding: 0 20px;
}

.title-text::before,
.title-text::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 30px;
  height: 2px;
  background-color: #409EFF;
}

.title-text::before {
  left: -20px;
}

.title-text::after {
  right: -20px;
}

.range-list {
  display: grid;
  gap: 16px;
}

.range-item {
  background-color: #f8f9fa;
  border-radius: 10px;
  padding: 20px;
  border-left: 4px solid #409EFF;
  transition: transform 0.2s;
}

.range-item:hover {
  transform: translateY(-2px);
}

.range-header {
  margin-bottom: 12px;
}

.range-name {
  font-size: 18px;
  font-weight: 600;
  color: #409EFF;
}

.range-questions {
  font-size: 14px;
  color: #909399;
  margin-left: 8px;
}

.range-details {
  display: grid;
  gap: 8px;
}

.range-score,
.range-status,
.range-advice {
  font-size: 15px;
  color: #606266;
  line-height: 1.6;
}

.highlight {
  color: #409EFF;
  font-weight: 500;
}

.report-content {
  font-size: 15px;
  color: #606266;
  line-height: 1.8;
  white-space: pre-wrap;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

:deep(.el-button--large) {
  padding: 12px 24px;
  font-size: 16px;
  font-weight: 500;
}
</style>
